import React from 'react'
import { useEffect, useState, useRef } from 'react'
import CustomFrom from '@/components/CustomFrom'
import { useLocation, useNavigate } from 'react-router-dom'
import ReactQuill from "react-quill";
import { Button, message, Upload } from 'antd'
import { getUseridStoreInfo, setGoodsByStoreid, updateGoodsByStoreid } from '@/request/store'
import { upload } from '@/request/common'
import base from '@/utils/baseUrl'
import ImgCrop from 'antd-img-crop';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// import ImageResize from 'quill-image-resize-module-react';

// 使用前需注册
// Quill.register('modules/imageResize', ImageResize); // 注册图片缩放
import "react-quill/dist/quill.snow.css";
export default function Index() {
    const quilRef = useRef<any>(null)
    const location = useLocation()
    const navigate = useNavigate()
    const [fromDate, setFromDate]: any = useState({})
    const [selectList, setSelectList] = useState([])
    const [fileList, setInfo] = useState<UploadFile[]>([{
        uid: '-1',
        name: 'image.png',
        status: 'done',
        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    },])
    // 富文本编辑配置
    const modules = React.useMemo(
        () => ({
            toolbar: {
                container: [
                    [{ 'size': ['small', false, 'large', 'huge'] }],
                    [{ 'font': [] }],
                    [{ header: [1, 2, false] }],
                    ["bold", "italic", "underline", "strike", "blockquote"],
                    [{ 'align': [] }],
                    [
                        { list: "ordered" },
                        { list: "bullet" },
                        { indent: "-1" },
                        { indent: "+1" },
                    ],
                    [{
                        'background': ['rgb(  0,   0,   0)', 'rgb(230,   0,   0)', 'rgb(255, 153,   0)',
                            'rgb(255, 255,   0)', 'rgb(  0, 138,   0)', 'rgb(  0, 102, 204)',
                            'rgb(153,  51, 255)', 'rgb(255, 255, 255)', 'rgb(250, 204, 204)',
                            'rgb(255, 235, 204)', 'rgb(255, 255, 204)', 'rgb(204, 232, 204)',
                            'rgb(204, 224, 245)', 'rgb(235, 214, 255)', 'rgb(187, 187, 187)',
                            'rgb(240, 102, 102)', 'rgb(255, 194, 102)', 'rgb(255, 255, 102)',
                            'rgb(102, 185, 102)', 'rgb(102, 163, 224)', 'rgb(194, 133, 255)',
                            'rgb(136, 136, 136)', 'rgb(161,   0,   0)', 'rgb(178, 107,   0)',
                            'rgb(178, 178,   0)', 'rgb(  0,  97,   0)', 'rgb(  0,  71, 178)',
                            'rgb(107,  36, 178)', 'rgb( 68,  68,  68)', 'rgb( 92,   0,   0)',
                            'rgb(102,  61,   0)', 'rgb(102, 102,   0)', 'rgb(  0,  55,   0)',
                            'rgb(  0,  41, 102)', 'rgb( 61,  20,  10)']
                    }],
                    [{
                        'color': ['rgb(  0,   0,   0)', 'rgb(230,   0,   0)', 'rgb(255, 153,   0)',
                            'rgb(255, 255,   0)', 'rgb(  0, 138,   0)', 'rgb(  0, 102, 204)',
                            'rgb(153,  51, 255)', 'rgb(255, 255, 255)', 'rgb(250, 204, 204)',
                            'rgb(255, 235, 204)', 'rgb(255, 255, 204)', 'rgb(204, 232, 204)',
                            'rgb(204, 224, 245)', 'rgb(235, 214, 255)', 'rgb(187, 187, 187)',
                            'rgb(240, 102, 102)', 'rgb(255, 194, 102)', 'rgb(255, 255, 102)',
                            'rgb(102, 185, 102)', 'rgb(102, 163, 224)', 'rgb(194, 133, 255)',
                            'rgb(136, 136, 136)', 'rgb(161,   0,   0)', 'rgb(178, 107,   0)',
                            'rgb(178, 178,   0)', 'rgb(  0,  97,   0)', 'rgb(  0,  71, 178)',
                            'rgb(107,  36, 178)', 'rgb( 68,  68,  68)', 'rgb( 92,   0,   0)',
                            'rgb(102,  61,   0)', 'rgb(102, 102,   0)', 'rgb(  0,  55,   0)',
                            'rgb(  0,  41, 102)', 'rgb( 61,  20,  10)']
                    }],
                    [{ 'direction': 'rtl' }],
                    [{ 'script': 'sub' }, { 'script': 'super' }],
                    ["emoji", "link", "image"],
                    ["clean"],
                ],
                handlers: {
                    'image': () => imageHandle()
                },
            },
            clipboard: {
                matchers: [[]],
            },
            // imageResize: {
            //     // 调整图片尺寸
            //     displayStyles: {
            //         border: 'none',
            //     },
            //     modules: ['Resize', 'DisplaySize', 'Toolbar'],
            // },
        }),
        [],
    );
    const imageHandle = () => {
        const quillEditor = quilRef.current?.getEditor()
        const input: any = document.createElement('input')
        input.setAttribute('type', 'file')
        input.setAttribute('accept', 'image/*')
        input.click()
        input.onchange = async () => {
            const file = input.files[0]
            const formData: any = new FormData();
            formData.append('type', 5);
            formData.append('file', file);
            const res = await upload(formData)
            if (res.status === 200) {
                const range = quillEditor.getSelection()
                const link = res.data.url
                quillEditor.insertEmbed(range.index, 'image', link)
            } else {
                message.error('上传失败');
            }
        }
    }
    const getUseridStore = async () => {
        const res = await getUseridStoreInfo()
        setSelectList(res.data)
    }
    //发布
    const handlePub = () => {
        fromDate.submit()
    }
    const onFinish = async (value: any, errors: any[]) => {
        // details
        if (errors.length) return
        delete value.store.store_name
        if (value.store.area) delete value.store.area
        if (value.store.logo) delete value.store.logo
        if (value.store.address) delete value.store.address
        if (value.store.userid) delete value.store.userid
        value.store.details = quilRef.current?.value
        let res: any = {}
        if (location.state) {
            res = await updateGoodsByStoreid(value.store)
        } else {
            res = await setGoodsByStoreid(value.store)
        }
        if (res.status === 200) {
            message.success(location.state ? '修改成功' : '添加成功')
            fromDate.resetFields()
            if (location.state) navigate(-1)
        }
    }
    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };
    const handleChange: UploadProps['onChange'] = (info: any) => {
        let newFileList = [...info.fileList];
        newFileList = newFileList.slice(-2);
        newFileList = newFileList.map((file) => {
            if (file.response) {
                // Component will show file.url as link
                file.url = file.response.url;
            }
            return file;
        });

        setInfo(newFileList);
    };
    const onPreview = async (file: UploadFile) => {
        let src = file.url as string;
        if (!src) {
            src = await new Promise((resolve) => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj as RcFile);
                reader.onload = () => resolve(reader.result as string);
            });
        }
        const image = new Image();
        image.src = src;
        const imgWindow = window.open(src);
        imgWindow?.document.write(image.outerHTML);
    };
    useEffect(() => {
        if (location.state) {
            getUseridStore()
            quilRef.current.value = location.state.details
        }
    }, [])
    return (
        <div>
            <CustomFrom
                objName='store'
                onFinish={onFinish}
                selectList={selectList}
                type={['store', 'goods']}
                dictionaryName="pub"
                defaultValues={location.state}
                getDom={(f: any) => { setFromDate(f) }} />
            <div>
                <div style={{ padding: '20px 0', fontWeight: 'bold', fontSize: '20px' }}>展示图</div>
                <ImgCrop rotationSlider>
                    <Upload
                        name="file"
                        listType="picture-card"
                        className="avatar-uploader2"
                        showUploadList={false}
                        action={base + '/upload'}
                        beforeUpload={beforeUpload}
                        fileList={fileList}
                        onChange={handleChange}
                        onPreview={onPreview}
                        data={{ type: 5, oldPath: location.state ? location.state.img : '' }}
                        headers={{ "Authorization": localStorage.getItem('token') || '' }}
                    >
                        {fileList.length < 5 && '+ Upload'}
                    </Upload>
                </ImgCrop >
                <div style={{ padding: '20px 0', fontWeight: 'bold', fontSize: '20px' }}>产品详情{fileList.length}</div>
                <div>
                    <ReactQuill
                        ref={quilRef}
                        theme='snow'
                        style={{ minHeight: '300px' }}
                        modules={modules}
                        placeholder="请输入内容"
                    />
                </div>
            </div>
            <div className='flex flex-jc-fe'>
                <Button onClick={handlePub}>发布</Button>
            </div>
        </div>
    )
}
